'use strict';

webappApp.factory('thumbnailFactory', ['fileReaders', function(fileReaders) {
  return {
    create: function(file, onload, onprogress, onerror) {
      var reader = fileReaders.get();
      // Only process image files.
      if (!file.type.match('image.*') && onerror) {
        onerror('File must be of type image/*');
        return;
      }

      reader.onprogress = function (e) {
        var p;
        if (e.lengthComputable) {
          p = Math.round((e.loaded / e.total) * 100);
          if (angular.isNumber(p)) {
            onprogress(p);
          }
        }
      };

      // Closure to capture the file information.
      reader.onloadend = function (e) {
        if (e.target.readyState === reader.DONE) {
          onload(e.target.result);
        }
      };

      reader.onerror = function (e) {
        onerror(e);
      };

      // Read in the image file as a data URL.
      reader.readAsDataURL(file);
    }
  };
}])
.factory('fileReaders', function() {
  return {
    get: function () {
      return new FileReader();
    }
  };
});
